// 获取商品id
function getProductId() {
    let url = location.href
    let index = url.indexOf('?')
    let subUrl = url.substring(index + 1)
    let id = subUrl.split('=')[1]
    return id
}

// 获取商品数据
function getProductMesg() {
    let id = getProductId()
    $.ajax({
        url: `http://www.xiongmaoyouxuan.com/api/detail`,
        type: 'get',
        data: {
            id
        },
        success: function (result) {
            if (result.code == 200) {
                // 获取图片数据
                let goodsPic = result.data.detail.photo
                // 将图片数据存入本地
                goodsPic = JSON.stringify(goodsPic)
                localStorage.setItem('PICMESG', goodsPic)
                // 获取该商品信息
                let productItem = result.data.detail
                // 显示商品信息
                showProductMesg(productItem)
                // 创建商品对象
                let product = {
                    id: productItem.couponId,
                    name: productItem.title,
                    price: productItem.price,
                    img: productItem.image,
                    singlePrice: productItem.price,
                }
                operateProduct(product)
                // 获取商家信息
                let shopMesg = result.data.shop
                showShop(shopMesg)
                // 显示放大镜图片
                showMagnifier()
            }
        }
    })
}

// 显示放大镜图片
function showMagnifier() {
    let picMesg = localStorage.getItem('PICMESG')
    picMesg = JSON.parse(picMesg)
    let str = `
        <div class="left">
        <div class="show-box">
            <img class="on" src="${picMesg[0].url}" alt="">
            <div class="mask"></div>
        </div>
        <ul class="tab">
            <li class="active" data-index="1"><img src="${picMesg[0].url}" alt=""></li>
            <li data-index="2"><img src="${picMesg[1].url}" alt=""></li>
            <li data-index="3"><img src="${picMesg[2].url}" alt=""></li>
            <li data-index="4"><img src="${picMesg[3].url}" alt=""></li> 
            <li data-index="5"><img src="${picMesg[4].url}" alt=""></li>    
        </ul>
    </div>
    <div class="right">
        <img src="${picMesg[0].url}" alt="">
    </div>  
    `
    $('.magnifier').html(str)

    let glass1 = new GlassZoom('#glassone')
    glass1.onTabGlass()
    glass1.moveGlass()
}

// 显示商品信息
function showProductMesg(productItem) {
    let str = `
        <img src = ''>
        <h3>${productItem.title}</h3>
        <hr>
        <div class="price">
            <div class="originPrice">
                <p>原价:</p><span>￥${productItem.originPrice}</span>
            </div>
            <div class="nowPrice">
                <p>现价:</p>￥<span>${productItem.price}</span>
            </div>
        </div>
        <div class="num">
            <div class = 'input'>
                <span>购买数量</span>
                <input type="button" name="minus" value="-"><input type="text" name="amount" value="1"><input type="button" name="plus" value="+">
            </div>
            <p>已售数量:${productItem.saleNum}</p>
        </div>
        <div class="btn" >
            <button class = 'add'>加入购物车</button>
            <button class = 'buy'>立即购买</button>
        </div> `
    $('.textMesg').html(str)
}

// 显示商家信息
function showShop(shopMesg) {
    let str = `
        <h3><span>—— </span>卖家信息<span> ——</span></h3>
        <img src="${shopMesg.picUrl}" alt="">
         <p>${shopMesg.nickname}</p>
        <div class = 'score'>
            <ul>
                <li>描述</li>
                <li class = 's'>${shopMesg.itemScore}</li>
            </ul>
            <ul>
                <li>服务</li>
                <li class = 's'>${shopMesg.serviceScore}</li>
            </ul>
            <ul>
                <li>物流</li>
                <li class = 's'>${shopMesg.deliveryScore}</li>
            </ul>
        </div>
    `
    $('.shop').html(str)
}

// 操作商品
function operateProduct(product) {
    product = {
        ...product,
        num: $('input[name="amount"]').val() == 0 ? 1 : $('input[name="amount"]').val(),
        state: false // 选中状态
    }
    // 加入购物车
    $('.textMesg').on('click', '.btn>.add', function () {
        let productStr = localStorage.getItem('CARTLIST')
        let carts = JSON.parse(productStr) || []
        let newProduct = carts.find((item) => item.id == product.id)
        if (newProduct) {
            // 如果已经存在，改变商品数量
            // 如果输入框的值为0
            if ($('input[name="amount"]').val() == 0) {
                newProduct.num++
                newProduct.singlePrice = (newProduct.num * newProduct.price).toFixed(2)
            } else {
                newProduct.num = Number(newProduct.num) + Number($('input[name="amount"]').val())
                newProduct.singlePrice = (newProduct.num * newProduct.price).toFixed(2)
            }
        } else {
            // 如果不存在，添加一项商品
            carts.push(product)
            if ($('input[name="amount"]').val() != 0) {
                product.num = Number($('input[name="amount"]').val())
                product.singlePrice = (product.num * product.price).toFixed(2)
            }
        }
        // 已经添加数据的数组重新写回localstorage
        localStorage.setItem('CARTLIST', JSON.stringify(carts))
        alert('添加购物车成功!')
        location.href = '../pages/cart.html'
    })

    // 商品按钮加加
    $('.textMesg').on('click', 'input[name="plus"]', function () {
        product.num++
        // 解除减按钮的禁制
        $(this).prev().prev().removeAttr('disabled')
        $('input[name="amount"]').val(product.num)
    })

    // 商品按钮减减
    $('.textMesg').on('click', 'input[name="minus"]', function () {
        product.num--
        if (product.num == 0) {
            $(this).attr('disabled', 'disabled')
        }
        $('input[name="amount"]').val(product.num)
    })

    // 立即购买
    $('.textMesg').on('click', '.btn>.buy', function () {
        alert('该功能暂未开发，请先跳转至购物车')
    })
}
getProductMesg()